package com.yygo.webapp.controller.material;

import com.yygo.Constants;
import com.yygo.model.LoanRequest;
import com.yygo.model.MaterialAudit;
import com.yygo.model.User;
import com.yygo.model.enums.MaterialStatus;
import com.yygo.model.enums.Phase;
import com.yygo.service.LoanProductManager;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.MaterialAuditManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;

/**
 * Created by tiansha on 2015/10/31.
 */
@Controller
@RequestMapping("/printMaterialsForm")
public class PrintMaterialsFormController extends BaseMaterialController {

    @Autowired
    private MaterialAuditManager materialAuditManager;

    @Autowired
    private LoanRequestManager loanRequestManager;

    @Autowired
    private UserManager userManager;

    @RequestMapping(method = RequestMethod.GET)
    public String audit(@RequestParam(required = true, value = "maId") Long maId,
                               Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.Material_Print_ROLE)) {
            throw new AccessDeniedException("You have no right to set material complete");
        }
        MaterialAudit materialAudit = materialAuditManager.get(maId);
        //materialAudit.getLoanRequest().setPhase(Phase.bank_loan_audit);
        materialAudit.setMaterialStatus(MaterialStatus.Complete);
        materialAuditManager.save(materialAudit);

        LoanRequest loanRequest = loanRequestManager.loadWholeLoanRequest(materialAudit.getLoanRequest().getId());
        loanRequest.setPhase(Phase.bank_loan_audit);
        loanRequestManager.saveLoanRequest(loanRequest);

        return "redirect:/materialPrintList";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String reject(@RequestParam(required = true, value = "maId") Long maId,
                         Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.Material_Print_ROLE)) {
            throw new AccessDeniedException("You have no right to reject material print");
        }
        MaterialAudit materialAudit = materialAuditManager.get(maId);
        materialAudit.setMaterialStatus(MaterialStatus.Auditing);
        materialAuditManager.save(materialAudit);
        return "redirect:/materialPrintList";
    }
}
